package system.controller;

import common.controller.base.BaseController;
import common.model.po.SysAuthority;
import common.model.po.SysRole;
import common.model.response.base.Result;
import common.service.RedissonCacheService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.redisson.api.RMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import system.model.request.SaveRoleAuthorityRequest;
import system.service.SysAuthorityService;
import system.service.SysRoleService;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * 权限管理
 *
 * @author 米泽鹏
 * @since 2022-03-11
 */
@Api(tags = "权限管理")
@RestController
@RequestMapping("/system/sys-authority")
public class SysAuthorityController extends BaseController {

	@Resource
	private SysAuthorityService authorityService;
	@Resource
	private SysRoleService roleService;
	@Resource
	private RedissonCacheService redissonCacheService;

	@ApiOperation(value = "查询权限树所需信息", notes = "查询权限树所需信息")
	@PostMapping("/readOnly/getAuthorityInfo")
	public Result<?> getAuthorityInfo() {
		return successWithData(authorityService.getAuthorityInfoFromCache());
	}

	@ApiOperation(value = "权限新增或更新", notes = "权限新增或更新")
	@PostMapping("/saveAuthority")
	public Result<?> saveAuthority(@ApiParam(value = "权限信息实体类", required = true) @RequestBody @Validated SysAuthority po) {
		return authorityService.saveAuthority(po);
	}

	@ApiOperation(value = "权限删除", notes = "权限删除")
	@DeleteMapping("/deleteAuthority/{id}")
	public Result<?> deleteAuthority(@ApiParam(value = "权限id", required = true) @PathVariable Long id) {
		return authorityService.deleteAuthority(id);
	}

	@ApiOperation(value = "根据角色id查询该角色所有权限", notes = "根据角色id查询该角色所有权限")
	@GetMapping("/readOnly/getAllAuthorityIdByRoleId/{id}")
	public Result<Set<Long>> getAllAuthorityIdByRoleId(@ApiParam(value = "角色id", required = true) @PathVariable Long id) {
		// 从缓存中获取菜单数据
		RMap<Long, Set<Long>> byRoleIdMap = redissonCacheService.getAllAuthIdCacheByRoleId();
		Set<Long> authIdSet = byRoleIdMap.get(id);
		return successWithData(authIdSet);
	}

	@ApiOperation(value = "角色分配权限保存", notes = "角色分配权限保存")
	@PostMapping("/saveRoleAuthority")
	public Result<?> saveRoleAuthority(@ApiParam(value = "角色分配权限保存请求", required = true) @RequestBody @Validated SaveRoleAuthorityRequest request) {
		return authorityService.saveRoleAuthority(request);
	}

	@ApiOperation(value = "查询所有角色", notes = "查询所有角色")
	@GetMapping("/readOnly/getAllRole")
	public Result<List<SysRole>> getAllRole() {
		return successWithData(roleService.list());
	}

}
